<template>
    <div class="taskAdd-wrap">
        <div class="title-top-box">
            <img src="../../assets/images/taskadd/icn.png" @click="clickOut" />
            <h2>{{ dialogTitle }}</h2>
            <p style="visibility: hidden;">凑四个字</p>
        </div>
        <div class="content-top-box">
            <div class="content-item">
                <img src="../../assets/images/taskadd/tasktitle.png" />
                <van-field v-model="taskForm.taskInfo.title" label="任务标题" placeholder="请输入" />
            </div>
            <div class="content-bottom">
                <img src="../../assets/images/taskadd/content.png" />
                <van-field v-model="taskForm.taskInfo.content" rows="2" autosize label="任务内容" type="textarea" maxlength="50"
                    placeholder="请输入" />
            </div>
        </div>
        <div class="content-middle-box">
            <div class="record-item">
                <img src="../../assets/images/taskadd/record.png" />
                <p>录音</p>
                <div class="tag-item">
                    <van-tag type="primary" color="#E8F1FF" text-color="#3F8CFF" size="large"
                        style="margin-right: 0.8rem;padding: 0.5rem 0.7rem 0.5rem;border-radius: 5px;"
                        @click="startRecordAudio">开始</van-tag>
                    <van-tag type="primary" color="#F9E6FC " text-color="#C418E6 " size="large"
                        style="margin-right: 0.8rem;padding: 0.5rem 0.7rem 0.5rem;border-radius: 5px;"
                        @click="stopRecordAudio">停止</van-tag>
                    <van-tag type="primary" color="#E0F9F2" text-color="#00D097" size="large"
                        style="margin-right: 0.8rem;padding: 0.5rem 0.7rem 0.5rem;border-radius: 5px;"
                        @click="playRecordAudio">播放</van-tag>
                    <van-tag type="primary" color="#F9F5E0" text-color="#EEB84F" size="large"
                        style="padding: 0.5rem 0.7rem 0.5rem;border-radius: 5px;" @click="handlePausePlay">暂停</van-tag>
                </div>
            </div>
            <!-- 图片 -->
            <div class="image-item">
                <van-uploader v-model="fileList" multiple :max-count="3" :max-size="5 * 1024 * 1024"
                    :before-read="beforeRead" :after-read="clzpAfterRead" @oversize="onOversize" @delete="deleteClzp" />
            </div>
        </div>

        <div class="content-bottom-box">

            <!-- 工作类型 -->
            <div class="type-item">
                <img src="../../assets/images/taskadd/type.png" />
                <van-field v-model="typeData" is-link readonly label="工作分类" placeholder="请选择" @click="showType = true" />
                <van-popup v-model:show="showType" round position="bottom">
                    <van-picker :columns="classify" title="选择任务类型" @cancel="showType = false" @confirm="clickType" />
                    <!-- v-model="taskForm.taskInfo.classify" -->
                </van-popup>
                <!-- <div class="item-left">
                    <img src="../../assets/images/taskadd/type.png" />
                    <p>工作分类</p>
                </div>
                <div class="item-right">
                    <p>请选择</p>
                    <img src="../../assets/images/taskadd/right_arrow.png" />
                </div> -->
            </div>

            <!-- 优先级 -->
            <div class="type-item">
                <img src="../../assets/images/taskadd/priority.png" />
                <van-field v-model="priorityData" is-link readonly label="优先等级" placeholder="请选择"
                    @click="showPriority = true" />
                <van-popup v-model:show="showPriority" round position="bottom">
                    <van-picker :columns="priority" title="选择任务优先级" @cancel="showPriority = false"
                        @confirm="clickPriority" />
                    <!-- v-model="taskForm.taskInfo.classify" -->
                </van-popup>
            </div>
            <!-- 执行人 -->
            <div class="type-item">
                <img src="../../assets/images/taskadd/executors.png" />
                <van-field v-model="executorData" is-link readonly label="执行人" placeholder="请选择" @click="showExecutor" />

            </div>
            <!-- 提醒时间 -->
            <div class="type-item">
                <img src="../../assets/images/taskadd/reminderTime.png" />
                <van-field v-model="reminderTimeData" is-link readonly label="提醒时间" placeholder="请选择"
                    @click="showReminderTime = true" />
                <van-popup v-model:show="showReminderTime" round position="bottom">
                    <van-picker :columns="reminderTime" title="选择提醒时间" @cancel="showReminderTime = false"
                        @confirm="clickReminderTime" />
                    <!-- v-model="taskForm.taskInfo.classify" -->
                </van-popup>
            </div>

            <!-- 截至时间 -->
            <div class="type-item">
                <img src="../../assets/images/taskadd/deadline.png" />
                <van-field v-model="taskForm.taskInfo.deadline" is-link readonly label="截至时间" placeholder="请选择"
                    @click="showDeadline = true" />
                <van-popup v-model:show="showDeadline" round position="bottom">
                    <van-picker-group title="截至时间" :tabs="['选择日期', '选择时间']" @confirm="onConfirm" @cancel="onCancel">
                        <van-date-picker v-model="currentDate" :min-date="minDate" :max-date="maxDate" />
                        <van-time-picker v-model="currentTime" />
                    </van-picker-group>
                </van-popup>
            </div>
        </div>
        <div class="btn-box">
            <van-button type="primary" color="#3F8CFF" @click="submit">创建任务</van-button>
        </div>
        <!-- 打开类型选择弹窗 -->
    </div>
</template>

<script setup name="taskAdd">
import { reactive, ref, computed } from 'vue';
import { addTask, getListGroup, fileUpload, deleteFile, taskDetail } from '../../api/index'
import { useRouter, useRoute } from "vue-router";
import Recorder from "js-audio-recorder";
import { executorWithOut } from '../../store/modules/excutor'
import { showToast,showSuccessToast,showFailToast } from 'vant';
import 'vant/es/toast/style';
import { store } from '../../store';


let router = useRouter()
let route = useRoute()


//store
const userStore = executorWithOut();
// const userExecutor = computed(() => {
//     return userStore.getUserExecutor
// })
// //获取缓存taskData数据
// const userTaskData = computed(() => {
//     return userStore.getUserTaskData
// })
// const userDialogTitles = computed(() => {
//     return userStore.setUserDialogTitle
// })
// const { taskData,executor,dialogData} = storeToRefs(userStore)


const dialogTitle = ref();
//任务类型
const typeData = ref()
// 弹窗控制
const showType = ref(false);
const classify = [
    { text: '前期工作', value: '0' },
    { text: '质量安全', value: '1' },
    { text: '综合管理', value: '2' },
    { text: '上级交办', value: '3' },
    { text: '对外协调', value: '4' },
    { text: '对上汇报', value: '5' },
];


//任务优先级
const priorityData = ref()
let showPriority = ref(false)
const priority = [
    { text: '紧急事务(1级)', value: '0' },
    { text: '一般事务(2级)', value: '1' },
    { text: '待办事务(3级)', value: '2' },
]

//提醒时间
let reminderTimeData = ref()
let showReminderTime = ref(false)
let reminderTime = [
    { text: '1小时', value: '1' },
    { text: '6小时', value: '6' },
    { text: '12小时', value: '12' },
    { text: '24小时', value: '24' },
    { text: '3天', value: '72' },
    { text: '7天', value: '168' },
]
//截至时间
let showDeadline = ref(false)
const currentDate = ref(['2022', '06', '01']);
const currentTime = ref(['12', '00']);
let minDate = new Date(2023, 1, 1)
let maxDate = new Date(2025, 5, 1)



//执行人
let executorData = ref([])
// 任务ID 
let taskId = route.query.id
const taskForm = reactive(
    {
        executors: [],  //执行人ID和姓名的数组
        files: [], //录音图片地址
        taskInfo: {
            id: '',
            title: '',
            createName: '',
            content: '', //任务描述
            classify: '',
            priority: '',
            reminderTime: '',  //时间提醒
            deadline: '',
            state: 0, //任务状态 0待办 1已办 2超期未完成
            imageUrl: [],  //图片地址
            recordUrl: [],  //录音地址
        },
    }
)
const imageUrl = ref([])  //默认图片
const recordUrl = ref([]) //默认录音



//重置
function taskRuleFormRest() {
    taskForm.taskInfo.id = undefined;
    taskForm.taskInfo.title = undefined;
    taskForm.taskInfo.createName = undefined;
    taskForm.taskInfo.content = undefined;
    taskForm.taskInfo.classify = undefined;
    taskForm.taskInfo.priority = undefined;
    taskForm.taskInfo.reminderTime = undefined;
    taskForm.taskInfo.deadline = undefined;
    taskForm.taskInfo.state = 0;
    taskForm.taskInfo.imageUrl = [];
    taskForm.taskInfo.recordUrl = [];

    taskForm.files = [];
    taskForm.executors = [];

    // dataForm.imageUrl = []
    // dataForm.recordUrl = []
    // nodeData.value = undefined;
    dialogTitle.value = undefined
    executorData.value = []
}



// 路由离开前的操作
onBeforeRouteLeave((to, from, next) => {
    // 判断数据是否有更改
    if (from.name == 'taskAdd') {
        if (to.name == 'selectPeople') {
            from.meta.keepAlive = true;
            userStore.setUserTaskData(taskForm)

            userStore.setUserDialogTitle(dialogTitle.value)

            const data = {
                fileList: fileList.value,
                clzpfilePath: clzpfilePath.value
            }
            userStore.setUserFile(data)
        } else {
            from.meta.keepAlive = false;
            userStore.$reset()
            // userStore.setUserTaskData(null)
            // userStore.setUserDialogTitle(null)
        }
    }
    next();
});

//录音相关
// let recordUrl = ref([])
const recorder = new Recorder({
    sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
    sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
    numChannels: 2, // 声道，支持 1 或 2， 默认是1
    // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
})

//开始录音
const startRecordAudio = () => {
    if (taskForm.taskInfo.recordUrl.length == 0) {

        recorder.start(); // 开始录音
        alert("开始录音")
        Recorder.getPermission().then(
            () => {
                alert("给权限了")
                recorder.start(); // 开始录音
            },
            (error) => {
                // console.log("请先允许该网页使用麦克风");
                // console.log(`${error.name} : ${error.message}`);
            }
        )
    } else {
        showToast('无法重复录制')
    }
}
//停止录音
const stopRecordAudio = () => {
    alert("停止录音");
    recorder.stop();
    uploadWAVData()
}
//播放录音
const playRecordAudio = () => {
    // console.log("播放录音");
    alert("播放录音");
    recorder.play();
}
// 暂停播放
const handlePausePlay = () => {
    // console.log("暂停播放");
    alert("暂停播放");
    recorder.pausePlay();
}
//   上传wav录音数据
const uploadWAVData = () => {
    if (taskForm.taskInfo.recordUrl.length == 0) {
        let wavBlob = recorder.getWAVBlob();
        // 创建一个formData对象
        let formData = new FormData()
        // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
        const newbolb = new Blob([wavBlob], { type: 'audio/wav' })
        //获取当时时间戳作为文件名
        const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
        formData.append('file', fileOfBlob)
        fileUpload(formData).then((response) => {
            taskForm.taskInfo.recordUrl.push(response.data.data[0].url)
        });
    }
}
//清空录音
// const clearRecord = () =>{
//     record.value
// }


//图片相关
const fileList = ref([
    // {
    //     url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg',
    //     status: 'uploading',
    //     message: '上传中...',
    // },

])
const clzpfilePath = ref([]) //删除所需参数
// allowMultipleToast() 
const onOversize = (file) => {
    showToast("文件大小不能超过5MB");
}
//校验图片的格式
const beforeRead = (file) => {
    if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file.type)) {
        showToast("请上传正确格式的图片");
        return false;
    }
    return true;
}
//照片上传事件方法
const clzpAfterRead = (file) => {
    // console.log(fileList.value, 'fileList.value');
    // 上传状态提示开启
    file.status = "uploading";
    file.message = "上传中...";
    // 创建一个空对象实例
    let formData = new FormData();
    // 调用append()方法添加数据
    formData.append("file", file.file);
    fileUpload(formData).then(({ data }) => {
        if (data.code == "200") {
            // 上传状态提示关闭
            file.status = "done";
            showToast("上传成功！");
            clzpfilePath.value.push(data.data[0]) //删除所需参数
            // console.log(data.data[0], 'clzpfilePath.value2');
            taskForm.taskInfo.imageUrl.push(data.data[0])
            // console.log(taskForm.taskInfo.imageUrl, 'clzpfilePath.value');
        }
    });
}
//照片删除事件方法
const deleteClzp = (file) => {
    let data = file
    if (data.file == undefined) {
        file = {}
        file.file = data
    }
    // console.log(file, '111');
    clzpfilePath.value.forEach(e => {
        if (e.name == file.file.name) {
            // console.log(e.url)
            deleteFile(e.url).then((res) => {
                if (res.code == "200") {
                    showToast("删除成功！");

                }
            })
        }
    })
    clzpfilePath.value = clzpfilePath.value.filter(item => item.name != file.file.name)
    taskForm.taskInfo.imageUrl = taskForm.taskInfo.imageUrl.filter(item => item.name != file.file.name)
    // console.log(taskForm.taskInfo.imageUrl, 'clzpfilePath.value');
    // console.log(clzpfilePath.value, 'clzpfilePath.value2');
    // console.log(fileList.value, 'clzpfilePath.value3');
    // filePath：删除所需的参数
}


//工作分类完成
const clickType = ({ selectedOptions }) => {
    showType.value = false;
    typeData.value = selectedOptions[0].text
    taskForm.taskInfo.classify = selectedOptions[0].value;
};
//优先级
const clickPriority = ({ selectedOptions }) => {
    showPriority.value = false;
    priorityData.value = selectedOptions[0].text
    taskForm.taskInfo.priority = selectedOptions[0].value;
    // console.log(taskForm.taskInfo, 'taskForm.taskInfo.priority');
}
//执行人
const showExecutor = () => {
    //     userStore.setUserTaskData(taskForm)
    //     console.log(userStore.getUserExecutor, '111');
    // taskRuleFormRest()
    executorData.value = []
    router.push({
        name: 'selectPeople',
    })
}
//时间提醒
const clickReminderTime = ({ selectedOptions }) => {
    showReminderTime.value = false;
    taskForm.taskInfo.reminderTime = selectedOptions[0].value;
    reminderTimeData.value = selectedOptions[0].text
}

//截止时间
const onConfirm = () => {
    taskForm.taskInfo.deadline = `${currentDate.value.join('-')} ${currentTime.value.join(':')}:00`
    console.log( taskForm.taskInfo.deadline,' taskForm.taskInfo.deadline');
    showDeadline.value = false
};
const onCancel = () => {
};

//创建任务
const submit = () => {
    // console.log(taskForm, '111');
    if (taskForm.taskInfo.imageUrl.length != 0) {
        taskForm.files = taskForm.taskInfo.imageUrl.map(item => {
                return item
            })
        }
        if (taskForm.taskInfo.recordUrl.length != 0) {
            taskForm.files.push(taskForm.taskInfo.recordUrl[0])
        }
    addTask(taskForm).then((res) => {
      
        taskRuleFormRest()
        //关闭弹窗
        if (res.data.code != 200) {
            showFailToast('添加失败');
        } else {
            showSuccessToast('成功文案');
            getList()
        }
    })
    // taskForm.taskInfo.title = null
}




//初始化格式
const reFormat = (val) => {
    // console.log(val, 'val.classsify');
    switch (val.classify) {
        case '0':
            typeData.value = '前期工作'
            break;
        case '1':
            typeData.value = '质量安全'
            break;
        case '2':
            typeData.value = '综合管理'
            break;
        case '3':
            typeData.value = '上级交办'
            break;
        case '4':
            typeData.value = '对外协调'
            break;
        case '5':
            typeData.value = '对上汇报'
            break;
    }
    switch (val.priority) {
        case '0':
            priorityData.value = '紧急事务(1级)'
            break;
        case '1':
            priorityData.value = '一般事务(2级)'
            break;
        case '2':
            priorityData.value = '待办事务(3级)'
            break;
    }

    switch (val.reminderTime) {
        case '1':
            reminderTimeData.value = '1小时'
            break;
        case '6':
            reminderTimeData.value = '6小时'
            break;
        case '12':
            reminderTimeData.value = '12小时'
            break;
        case '24':
            reminderTimeData.value = '24小时'
            break;
        case '72':
            reminderTimeData.value = '3天'
            break;
        case '168':
            reminderTimeData.value = '7天'
            break;
    }
}
//初始化数据
const getList = () => {
    dialogTitle.value = route.query.dialogTitle
    if (dialogTitle.value == "添加任务") {
        // taskForm.executors = userExecutor
        executorData.value = taskForm.executors[0] ? taskForm.executors[0].empName + `等` : null
        // console.log(taskForm.executors[0], 'taskForm.executors');
        return;
    } else {
        taskDetail(taskId).then(res => {
            if (res.data.code == 200) {
                // console.log(res.data.data.executors,'taskForm');
                const data = detailEcho(res.data.data)

                taskForm.executors = data.executors
                taskForm.taskInfo = data.taskInfo
                taskForm.taskInfo.recordUrl = data.files
                taskForm.taskInfo.imageUrl = data.images
                fileList.value = data.images
                clzpfilePath.value = data.images //删除照片
                // console.log(data.executors,' data.executors[0]');
                executorData.value = data.executors[0] ? data.executors[0].empName + `等` : null
                reFormat(taskForm.taskInfo)
                // console.log(taskForm, 'taskForm');
            }
        })
    }
}

const getCache = () => {
    const { taskData, dialogData, fileData, executor } = storeToRefs(userStore)
    // console.log(taskData.value.executors, ' dialogData.value123')

    dialogTitle.value = dialogData.value
    taskForm.taskInfo = taskData.value.taskInfo
    reFormat(taskForm.taskInfo)
    // taskForm.executors = taskData.value.executors
    taskForm.executors = executor.value
    // taskForm.executors.forEach(item => {
    //     if (item.fullName != undefined) {
    //         item.empName = item.fullName
    //         item.empId = item.id
    //     }
    // })
    executorData.value = taskForm.executors[0] ? taskForm.executors[0].empName + `等` : null
    fileList.value = fileData.value.fileList
    clzpfilePath.value = fileData.value.clzpfilePath
    // // taskForm.taskInfo.recordUrl = userTaskData.files
    // // taskForm.taskInfo.imageUrl = userTaskData.images
    // executorData.value = userExecutor
    // console.log(dialogTitle.value, ' dialogData.value123')
    // console.log(taskForm, ' taskForm')
    // console.log(typeData.value, ' taskForm')
}

//点击退出
const clickOut = () => {
    executorData.value = []
    // taskRuleFormRest()
    // clzpfilePath.value.forEach(e => {
    //     if (e.name == file.file.name) {
    //         deleteFile(e.url).then((res) => {
    //             if (res.code == "200") {
    //             }
    //         })
    //     }
    // })
    router.push({
        path: '/taskList'
    })
}


//查看回显
const detailEcho = (val) => {
    // console.log(val, 'aaaaa')
    let data1 = []
    let data2 = []
    val.files.forEach(e => {
        let obj = {}
        obj.ext = e.fileName
            .substring(e.fileName.lastIndexOf(".") + 1)
            .toLowerCase();
        obj.size = e.fileSize
        obj.name = e.fileName
        obj.url = `${e.fileUrl}` + `${e.fileName}`
        obj.url = obj.url.replace(undefined, '')
        data1.push(obj)
    })
    val.images.forEach(e => {
        let obj = {}
        obj.ext = e.imageName
            .substring(e.imageName.lastIndexOf(".") + 1)
            .toLowerCase();
        obj.size = e.imageSize
        obj.name = e.imageName
        obj.url = `${e.imageUrl}` + `${e.imageName}`
        obj.url = obj.url.replace(undefined, '')
        data2.push(obj)
    })
    val.files.splice(0, val.files.length)
    val.images.splice(0, val.images.length)
    val.files = data1
    val.images = data2
    return val
}

onMounted(() => {
    if (!route.meta.keepAlive) {
        getList();
    } else {
        console.log(' dialogData.value123')
        getCache()
    }
    // getList();
});

</script>

<style scoped lang="scss">
.title-top-box {
    width: 100%;
    background-color: #FFFFFF;
    display: flex;
    justify-content: space-around;
    align-items: center;


    img {
        width: 2rem;
        height: 2rem;
        margin-left: -1rem;
    }

    h2 {
        margin-left: 3rem;
        font-size: 1.5rem;
    }

    p {
        color: #3F8CFF;
        font-weight: lighter;
        margin: 0 -1rem -0.2rem 0;
        font-size: 1rem;
    }
}

img {
    width: 2rem;
    height: 2rem;
}

p {
    font-size: 17px;
    color: #666666;
}

.content-top-box {
    padding: 0.4rem 1rem 0 1rem;
    margin-top: 2rem;
    width: 100%;
    background-color: #FFFFFF;


    .content-item {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #d8d4d4;
        padding-bottom: 0.5rem;
    }
}

:deep(.van-field) {
    .van-field__label {
        color: #666666;
        font-size: 17px;
    }

    .van-field__control {
        margin-left: -2rem;
    }
}

.content-bottom {
    display: flex;
    align-items: flex-start;
    margin-top: 0.5rem;

    img {
        margin-top: 0.3rem;
    }
}

.content-middle-box {
    padding: 1rem 1rem 0.1rem 1rem;
    margin-top: 1.2rem;
    width: 100%;
    background-color: #FFFFFF;
}

.record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #d8d4d4;
    padding-bottom: 1.2rem;

    p {
        margin-left: -1.5rem;
    }
}

.image-item {
    margin: 1rem 0 0.5rem;
}

.content-bottom-box {
    padding: 0.5rem 1rem 0.1rem 1rem;
    margin-top: 1.2rem;
    width: 100%;
    background-color: #FFFFFF;

    .type-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #d8d4d4;

        padding: 0.8rem 0 0.5rem 0;

        p {
            margin: 0.2rem 0 0 1rem;
        }

        .item-left {
            display: flex;
            align-items: center;
        }

        .item-right {
            display: flex;
            align-items: center;

            p {
                color: #ccc8c8;
            }
        }

    }
}

:deep(.van-picker__title) {
    font-size: 1.3rem;
    font-weight: lighter;
}

:deep(.van-ellipsis .van-tab) {
    font-weight: lighter;
}

.btn-box {
    padding: 1rem 2rem;
    margin-top: 1rem;
    width: 100%;
    background-color: #FFFFFF;

    .van-button {
        border-radius: 0.9rem;
        width: 100%;
    }
}

.van-toast {
    //   background-color: rgb(132, 129, 129);
}
</style>